import { useState, useEffect } from 'react';
import { Task } from '../types';
import { v4 as uuidv4 } from 'uuid';

// 示例任务数据
const initialTasks: Task[] = [
  {
    id: uuidv4(),
    title: '完成项目报告',
    description: '完成四象限项目的详细报告',
    deadline: new Date(Date.now() + 24 * 60 * 60 * 1000), // 明天
    completed: false,
    priority: 'high',
    quadrant: 1, // 重要且紧急
    createdAt: new Date()
  },
  {
    id: uuidv4(),
    title: '学习React新特性',
    description: '学习React 18的新特性和用法',
    deadline: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 一周后
    completed: false,
    priority: 'medium',
    quadrant: 2, // 重要不紧急
    createdAt: new Date()
  },
  {
    id: uuidv4(),
    title: '回复邮件',
    description: '回复所有未读邮件',
    deadline: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000), // 两天后
    completed: false,
    priority: 'medium',
    quadrant: 3, // 紧急不重要
    createdAt: new Date()
  },
  {
    id: uuidv4(),
    title: '整理文件夹',
    description: '整理电脑桌面和文件夹',
    deadline: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000), // 两周后
    completed: false,
    priority: 'low',
    quadrant: 4, // 不重要不紧急
    createdAt: new Date()
  }
];

export const useTaskManager = () => {
  const [tasks, setTasks] = useState<Task[]>(initialTasks);

  // 在组件挂载时，尝试从localStorage加载任务
  useEffect(() => {
    const savedTasks = localStorage.getItem('quadrantTasks');
    if (savedTasks) {
      try {
        const parsedTasks = JSON.parse(savedTasks);
        // 将字符串日期转换回Date对象
        const formattedTasks = parsedTasks.map((task: any) => ({
          ...task,
          deadline: task.deadline ? new Date(task.deadline) : undefined,
          createdAt: new Date(task.createdAt)
        }));
        setTasks(formattedTasks);
      } catch (error) {
        console.error('加载任务失败:', error);
      }
    }
  }, []);

  // 当任务更新时保存到localStorage
  useEffect(() => {
    localStorage.setItem('quadrantTasks', JSON.stringify(tasks));
  }, [tasks]);

  // 移动任务
  const moveTask = (
    sourceQuadrant: number,
    sourceIndex: number,
    destQuadrant: number,
    destIndex: number
  ) => {
    setTasks(prevTasks => {
      const newTasks = [...prevTasks];
      
      // 找到源象限中的任务
      const sourceTasks = newTasks.filter(task => task.quadrant === sourceQuadrant);
      
      // 找到要移动的任务
      const [movedTask] = sourceTasks.splice(sourceIndex, 1);
      
      // 更新任务的象限
      movedTask.quadrant = destQuadrant as 1 | 2 | 3 | 4;
      
      // 获取目标象限的任务
      const destinationTasks = newTasks.filter(task => task.quadrant === destQuadrant);
      
      // 将任务插入到目标位置
      destinationTasks.splice(destIndex, 0, movedTask);
      
      // 重建任务列表
      return [
        ...newTasks.filter(task => 
          task.quadrant !== sourceQuadrant && 
          task.quadrant !== destQuadrant
        ),
        ...sourceTasks.map(task => ({ ...task, quadrant: sourceQuadrant as 1 | 2 | 3 | 4 })),
        ...destinationTasks.map(task => ({ ...task, quadrant: destQuadrant as 1 | 2 | 3 | 4 }))
      ];
    });
  };

  // 切换任务状态
  const toggleTaskStatus = (taskId: string) => {
    setTasks(prevTasks => 
      prevTasks.map(task => 
        task.id === taskId 
          ? { ...task, completed: !task.completed } 
          : task
      )
    );
  };

  // 添加新任务
  const addTask = (title: string, quadrant: 1 | 2 | 3 | 4) => {
    if (!title.trim()) return;
    
    const newTask: Task = {
      id: uuidv4(),
      title,
      completed: false,
      priority: 'medium',
      quadrant,
      createdAt: new Date()
    };
    
    setTasks(prevTasks => [...prevTasks, newTask]);
  };

  // 模拟刷新任务列表
  const updateTasksList = () => {
    console.log('刷新任务列表');
    // 此处可以添加与后端API交互的逻辑
  };

  return {
    tasks,
    moveTask,
    toggleTaskStatus,
    addTask,
    updateTasksList
  };
}; 